<template>
  <view w-full box-border pa-20rpx rounded-20rpx pb-180rpx>
    <view mb-20rpx flex flex-col justify-center items-center py-20rpx bg-white>
      <image
        rounded-full
        w-200rpx
        h-200rpx
        :src="userInfo.face || '/static/default.png'"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            photoChangeSheet = true
          }
        " />
      <view
        v-if="routerValue?.isEdit != 2"
        bg="#EEEEEE"
        px-18rpx
        py-4rpx
        text-24rpx
        text="#7D7D7D"
        mt-25rpx
        rounded-full>
        点击修改头像
      </view>
    </view>
    <nut-cell-group>
      <nut-cell title="用户ID" :desc="userInfo.id"></nut-cell>
      <nut-cell
        title="昵称"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            $navigateTo('/pages/mine/operate?title=修改昵称&value=' + (userInfo.nickName || '') + '&type=nickName')
          }
        "
        :desc="userInfo.nickName"></nut-cell>
      <nut-cell
        title="性别"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            showSex = true
          }
        "
        :desc="userInfo.sex !== '' ? (userInfo.sex == 1 ? '男' : '女') : ''"></nut-cell>
      <nut-cell
        title="出生日期"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            showDate = true
          }
        "
        :desc="userInfo.birthday"></nut-cell>
      <nut-cell
        title="所在区域"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            picker()
          }
        "
        :desc="userInfo.region"></nut-cell>
      <nut-cell
        title="详细地址"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            $navigateTo(
              '/pages/mine/operate?title=详细地址&value=' + (userInfo.detailAddress || '') + '&type=detailAddress'
            )
          }
        "
        :desc="userInfo.detailAddress"></nut-cell>
      <nut-cell
        title="职业"
        @click="
          () => {
            if (routerValue?.isEdit == 2) return
            $navigateTo('/pages/mine/operate?title=职业&value=' + (userInfo.profession || '') + '&type=profession')
          }
        "
        :desc="userInfo.profession"></nut-cell>
    </nut-cell-group>
    <nut-popup position="bottom" v-model:visible="showSex">
      <nut-picker
        v-model="currentSex"
        swipe-duration="100"
        @cancel="showSex = false"
        @confirm="confirmSex"
        :columns="sexColumns"
        title="性别选择"></nut-picker>
    </nut-popup>
    <nut-popup position="bottom" v-model:visible="showDate">
      <nut-date-picker
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmDate"
        :is-show-chinese="true"></nut-date-picker>
    </nut-popup>
    <city ref="cityPicker" head-title="区域选择" picker-size="4" @funcValue="confirmCity" />

    <!-- 点击相册，选取图片得到图片本地路径即可 -->
    <nut-action-sheet
      cancel-txt="取消"
      v-model:visible="photoChangeSheet"
      :menu-items="[{ name: '相册 ' }]"
      @choose="choosePhoto"></nut-action-sheet>
  </view>
  <view v-if="routerValue?.isEdit != 2" position-fixed bottom-70rpx w-full z-999 px-40rpx box-border>
    <view
      w-670rpx
      h-100rpx
      rounded-50rpx
      bg="#D9D9D9"
      flex
      justify-center
      items-center
      font-500
      text="#000"
      text-32rpx
      @click="logout">
      退出登录
    </view>
  </view>
</template>

<script setup lang="ts">
import config from '@/config/config'
// import { getUserInfo, setUserInfo } from '@/api/login'
import { selectPersonalSetting, updatePersonalSetting } from '@/api/my'
import city from '@/components/m-city/m-city.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import storage from '@/utils/storage'
const showDate = ref(false)
const showSex = ref(false)
const cityPicker = ref<any>(null)
const currentSex = ref([0]) //当前性别
const photoChangeSheet = ref<boolean>(false)
const routerValue = ref<any>('')
const logoutVisible = ref(false)
const sexColumns = ref([
  { text: '男', value: 1 },
  { text: '女', value: 0 }
])
const minDate = new Date(1970, 0, 1)
const maxDate = new Date()
const userInfo = ref<any>({
  face: '',
  nickName: '',
  sex: '',
  mobile: '',
  birthday: '',
  region: '',
  id: '',
  detailAddress: '',
  profession: ''
})
// 城市选择
function picker() {
  cityPicker.value.show()
}
// 选择照片
function choosePhoto() {
  uni.chooseImage<UniApp.ChooseImageOptions>({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: function (res) {
      const tempFilePaths = res.tempFilePaths

      // 实际上这是一个文件流 把这个文件流存到storage里面
      storage.setBlobHex(tempFilePaths[0])
      photoChangeSheet.value = false
      uni.navigateTo({
        url: '/pages/mine/cropper-photo'
      })
    },
    fail: function (err) {
      photoChangeSheet.value = false
    }
  })
}

// 回调性别
function confirmSex({ selectedValue }: any) {
  userInfo.value.sex = selectedValue[0]
  showSex.value = false
  updateUserInfo()
}

// 回调时间
function confirmDate({ selectedValue }: any) {
  userInfo.value.birthday = `${selectedValue[0]}-${selectedValue[1]}-${selectedValue[2]}`
  showDate.value = false
  updateUserInfo()
}

// 回调城市
function confirmCity(val: any) {
  userInfo.value.region = val.map((item: any) => item.localName).join(',')
  userInfo.value.regionId = val.map((item: any) => item.id).join(',')
  updateUserInfo()
}

async function updateUserInfo() {
  const res = await updatePersonalSetting(userInfo.value)
  if (!res.data.success) {
    uni.showToast({
      title: '修改失败!',
      icon: 'none'
    })
  }
}

async function init() {
  const res = await selectPersonalSetting()
  if (res.data.success) {
    Object.keys(userInfo.value).forEach((key) => {
      userInfo.value[key] = res.data.result[key]
    })
    currentSex.value[0] = userInfo.value.sex || 0 //性别

    storage.setUserInfo(res.data.result)
  }
}

function logout() {
  uni.showModal({
    title: '提示',
    content: '退出将影响部分功能使用, 确认退出吗? ',
    confirmColor: '#FCC300',
    cancelColor: '#707175',
    success(res) {
      if (res.confirm) {
        storage.setAccessToken('')
        storage.setUuid('')
        storage.setUserInfo({})

        uni.navigateTo({
          url: '/pages/passport/wechatMPLogin'
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

onShow(() => {
  uni.$on('save', (val: any) => {
    userInfo.value[val.type] = val.value
    updateUserInfo()
    uni.$off('save')
  })
  init()
})
onLoad((val: any) => {
  routerValue.value = val
  console.log(routerValue.value)
})
</script>

<style scoped></style>
